from pymongo import MongoClient
from pymongo.errors import BulkWriteError
import json

def batch_insert_books(books):
    # 1. 连接 MongoDB（默认本地，无认证）
    client = MongoClient("mongodb://localhost:27017/")

    # 2. 选择数据库和集合
    db = client["test"]  # 数据库名
    collection = db["智慧阅读"]  # 集合名

    try:
        # 3. 批量插入（insert_many）
        result = collection.insert_many(books)
        print(f"成功插入 {len(result.inserted_ids)} 条图书数据！")
        print("插入的文档ID：", result.inserted_ids)

    except BulkWriteError as e:
        print("批量插入部分失败，详情：", e.details)
    except Exception as e:
        print("插入失败：", str(e))
    finally:
        # 4. 关闭连接
        client.close()


# 调用函数
with open('book.json', 'r', encoding='utf_8_sig') as f:
    books = json.load(f)  # Will work if file contains val
batch_insert_books(books)